﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Media;
using ViewMaker.Core.Utils;
using System.Xml.Serialization;
using System.ComponentModel;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
using System.Windows.Input;
using ViewMaker.Core.ViewModels;
using System.Collections;

namespace ViewMaker.Core.Controls
{
    [View(ViewControlType.Grid)]
#if SILVERLIGHT
    [ViewProperty(PanelViewControl.Properties.ItemWidth, 200)]
#endif
    public abstract class ViewElement : ViewModelBase, IViewLayoutGeneratorProvider
    {
        internal const string GeneralGroup = "General";
        internal const string LayoutGroup = "Layout";
        internal const string StyleGroup = "Style";
        internal const string CommandGroup = "Command";
        internal const string MiscGroup = "Misc";

        public class Properties
        {
        }

        [Browsable(false)]
        public ViewControlType ControlType { get; set; }

        [XmlIgnore]
        [Browsable(false)]

        public ViewLayoutItem Item
        {
            get { return _item; }
            set 
            {
                if (_item == value) return;
                if (_item != null) _item.PropertyChanged -= new PropertyChangedEventHandler(_item_PropertyChanged);
                _item = value;
                if (value != null) _item.PropertyChanged += new PropertyChangedEventHandler(_item_PropertyChanged);
            }
        }
        private ViewLayoutItem _item;

        void _item_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            ItemPropertyChanged(e);
        }
        protected virtual void ItemPropertyChanged(PropertyChangedEventArgs e)
        {
        }


        [XmlIgnore]
        [Display(Name = "", GroupName = MiscGroup)]
        [View(ViewControlType.Hyperlink)]
        [ViewProperty(HyperlinkViewControl.Properties.Command, "EditAdditionalPropertyCommand")]
        public string EditAdditionalPropertyLink { get { return "Additional Properties"; } }

        [XmlIgnore]
        [Browsable(false)]
        public Dictionary<string, string> AdditionalProperty
        {
            get { return _additionalProperty; }
        }
        private Dictionary<string, string> _additionalProperty = new Dictionary<string, string>();

        [Browsable(false), XmlArray("AdditionalProperty"), XmlArrayItem("AdditionalProperty", Type = typeof(DictionaryEntry))]
        public DictionaryEntry[] XmlAdditionalProperty
        {
            get
            {
                if (this.AdditionalProperty.Count == 0) return null;
                DictionaryEntry[] entryArray = new DictionaryEntry[this.AdditionalProperty.Count];
                int index = 0;
                foreach (KeyValuePair<string, string> pair in this.AdditionalProperty)
                {
                    entryArray[index] = new DictionaryEntry { Key = pair.Key, Value = pair.Value };
                    index++;
                }
                return entryArray;
            }
            set
            {
                this.AdditionalProperty.Clear();
                if (value != null)
                {
                    for (int i = 0; i < value.Length; i++)
                    {
                        this.AdditionalProperty.Add((string)value[i].Key, (string)value[i].Value);
                    }
                }
            }
        }

        [XmlIgnore]
        [Browsable(false)]
        public ICommand EditAdditionalPropertyCommand { get { return CreateCommand(EditAdditionalProperty); } }
        private void EditAdditionalProperty()
        {
            var vm = new StringDictionayEditViewModel(AdditionalProperty);
            foreach (var item in this.ControlType.GetAdditinalProperties())
            {
                vm.Keys.Add(item.Item1);
            }
            vm.PropertyChanged += new PropertyChangedEventHandler(AdditionalPropertyDailogPropertyChangedHandler);
            ViewUtil.ShowDialog(vm);

        }

        void AdditionalPropertyDailogPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
        {
            var dialog = sender as StringDictionayEditViewModel;
            if (e.PropertyName == "Key")
            {
                dialog.Values.Clear();

                var target = this.ControlType.GetAdditinalProperties().FirstOrDefault(x => x.Item1 == dialog.Key);
                if (target != null && target.Item2 != null)
                {
                    if (target.Item2.IsEnum)
                    {
                        TypeUtil.GetEnumNames(target.Item2).ForEach(x => dialog.Values.Add(x));
                    }
                    else if (target.Item2 == typeof(bool))
                    {
                        dialog.Values.Add(false.ToString());
                        dialog.Values.Add(true.ToString());
                    }
                }
            }
        }

        [XmlIgnore]
        [Display(Name = "", GroupName = MiscGroup)]
        [View(ViewControlType.Hyperlink)]
        [ViewProperty(HyperlinkViewControl.Properties.Command, "EditWindowSettingCommand")]
        [ViewProperty(HyperlinkViewControl.Properties.IsVisibile, "IsRootElement")]
        public string EditWindowSettingLink { get { return "Window Settings"; } }

        [XmlIgnore]
        [Browsable(false)]
        public ICommand EditWindowSettingCommand { get { return CreateCommand(EditWindowSetting); } }
        private void EditWindowSetting()
        {
            ViewUtil.ShowDialog(new DataEditViewModel<WindowSettings>(WindowSettings));

        }

        [Browsable(false)]
        public WindowSettings WindowSettings
        {
            get
            {
                if (_windowSettings == null)
                {
                    _windowSettings = new WindowSettings();
                }
                return _windowSettings;
            }
            set { _windowSettings = value; }
        }
        private WindowSettings _windowSettings;



        [XmlIgnore]
        [Browsable(false)]
        public bool IsPanel { get; set; }

        [XmlIgnore]
        [Browsable(false)]
        public bool IsDataGridItem { get; set; }

        [XmlIgnore]
        [Browsable(false)]
        public ObservableCollection<string> BindablePathList
        {
            get
            {
                return this.Item.BindablePathList;
            }
        }

        [XmlIgnore]
        [Browsable(false)]
        public bool IsRootElement
        {
            get { return this.Item.Parent == null; }
        }

        [XmlIgnore]
        [Browsable(false)]
        public bool IsCanvasElement
        {
            get { return this.Item.Parent != null && this.Item.Parent.ControlType == ViewControlType.Canvas; }
        }

        [XmlIgnore]
        [Browsable(false)]
        public bool IsGridElement
        {
            get { return this.Item.Parent != null && this.Item.Parent.ControlType == ViewControlType.Grid; }
        }

        [Browsable(false)]
        [XmlIgnore]
        public LayoutHorizontalAlignment[] HorizontalAlignmentList { get { return new LayoutHorizontalAlignment[] { LayoutHorizontalAlignment.Left, LayoutHorizontalAlignment.Right, LayoutHorizontalAlignment.Center, LayoutHorizontalAlignment.Stretch }; } }

        [Browsable(false)]
        [XmlIgnore]
        public LayoutVerticalAlignment[] VerticalAlignmentList { get { return new LayoutVerticalAlignment[] { LayoutVerticalAlignment.Top, LayoutVerticalAlignment.Bottom, LayoutVerticalAlignment.Center, LayoutVerticalAlignment.Stretch }; } }

        [Browsable(false)]
        [XmlIgnore]
        public LayoutOrientation[] OrientationList { get { return new LayoutOrientation[] { LayoutOrientation.Horizontal, LayoutOrientation.Vertical }; } }

        [Browsable(false)]
        [XmlIgnore]
        public LayoutHeaderPosition[] HeaderPositionList { get { return new LayoutHeaderPosition[] { LayoutHeaderPosition.Default, LayoutHeaderPosition.Left, LayoutHeaderPosition.Top, LayoutHeaderPosition.Hidden, LayoutHeaderPosition.Flat }; } }

        [Browsable(false)]
        [XmlIgnore]
        public LayoutDock[] DockList { get { return new LayoutDock[] { LayoutDock.Left, LayoutDock.Top, LayoutDock.Right, LayoutDock.Bottom }; } }

        [XmlIgnore]
        [Browsable(false)]
        public virtual bool CanOverrideWidth { get { return true; } }

        [XmlIgnore]
        [Browsable(false)]
        public virtual bool CanOverrideHeight { get { return true; } }

        [XmlIgnore]
        [Browsable(false)]
        public virtual bool CanAddChild { get { return false; } }

        [Browsable(false)]
        [XmlIgnore]
        public bool IsSilverlight { get; private set; }

        [Browsable(false)]
        [XmlIgnore]
        public bool IsWpf { get; private set; }

        [Browsable(false)]
        [XmlIgnore]
        public string[] ColorList
        {
            get { return typeof(Colors).GetProperties().Select(x => x.Name).ToArray(); }
        }



        public abstract List<XamlNode> CreateXaml(XamlNode parent);

        internal abstract void CopyFrom(ViewElement source);

        public ViewElement()
        {
#if !SILVERLIGHT
            IsWpf = true;
            IsSilverlight = false;
#else
            IsWpf = false;
            IsSilverlight = true;
#endif
        }

        #region ヘルパー

        protected void SetBindingAttribute(XamlNode parent, string attr, string path, bool oneWay)
        {
            if (string.IsNullOrEmpty(path)) return;

            if (path == ".")
            {
                path = "";
            }
            else
            {
                path = "Path=" + path + ",";
            }

            if (oneWay)
            {
                parent.SetAttribute(attr, "{Binding " + path + "Mode=OneWay}");
            }
            else
            {
                parent.SetAttribute(attr, "{Binding " + path + " Mode=TwoWay, ValidatesOnExceptions=True, ValidatesOnDataErrors=True, NotifyOnValidationError=True }");
            }
        }

        protected XamlNode AddBindingElement(XamlNode parent, string path, bool oneWay = false)
        {
            var node = parent.AddElement("Binding");
            node.SetAttribute("Path", path);
            node.SetAttribute("Mode", oneWay ? "OneWay" : "TwoWay");
            return node;
        }

        /// <summary>
        /// Viewコントロールの共通プロパティを設定する
        /// </summary>
        /// <param name="node"></param>
        protected virtual void ApplyBaseProperty(XamlNode node)
        {
            if (node == null) return;
            if (!string.IsNullOrWhiteSpace(Item.Name)) node.InsertAttribute(0, "Name", Item.Name);
#if !SILVERLIGHT
            if (!string.IsNullOrWhiteSpace(Item.Description)) node.SetAttribute("ToolTip", Item.Description);
#else
            if (!string.IsNullOrWhiteSpace(Item.Description))
            {
                node.AddElement("ToolTipService.ToolTip").AddElement("TextBlock").InnerText = Item.Description;
            }
#endif

            foreach (var tag in AdditionalProperty)
            {
                node.SetAttribute(tag.Key, tag.Value);
            }
        }

        protected string GetStringFormat(string format)
        {
            format = format.Replace("{", "\\{").Replace("}", "\\}");
            return format;
        }

        #endregion

        #region IViewLayoutGeneratorProvider メンバー

        ViewLayoutItem IViewLayoutGeneratorProvider.Generate()
        {
            var generator = ServiceLocator.GetService<IViewLayoutGenerator>();
            var layout = generator.Generate(this, LayoutGenerateFlag.LayoutData | LayoutGenerateFlag.SkipLoadError);
            if (layout != null) return layout;
            layout = generator.Generate(this, LayoutGenerateFlag.TypeInfo);

            var generalList = CreateItemListByGroup(layout, GeneralGroup, new string[] { null, "", GeneralGroup });
            var styleList = CreateItemListByGroup(layout, StyleGroup, new string[] { StyleGroup });
            var layoutList = CreateItemListByGroup(layout, LayoutGroup, new string[] { LayoutGroup });
            var commandList = CreateItemListByGroup(layout, CommandGroup, new string[] { CommandGroup });
            var miscList = CreateItemListByGroup(layout, MiscGroup, new string[] { MiscGroup });
            layout.Children.Clear();
            foreach (var item in generalList.Concat(styleList.Concat(layoutList.Concat(commandList.Concat(miscList)))))
            {
                layout.Children.Add(item);
            }
            return layout;
        }

        private List<ViewLayoutItem> CreateItemListByGroup(ViewLayoutItem root, string caption, string[] target)
        {
            bool first = true;
            List<ViewLayoutItem> newList = new List<ViewLayoutItem>();
            foreach (var item in root.Children.Where(x => target.Contains(x.Group)).OrderBy(x => x.Caption))
            {
                if (first)
                {
                    var groupHeader = new ViewLayoutItem(root, "header" + target[0], ViewControlType.Label, null, true, caption);
                    groupHeader.GetControl<LabelViewControl>().HeaderHorizontalContentAlignment = LayoutHorizontalAlignment.Left;
                    groupHeader.GetControl<LabelViewControl>().Background = Colors.LightGray.ToString();
                    groupHeader.GetControl<LabelViewControl>().HeaderBackground = Colors.LightGray.ToString();
                    groupHeader.GetControl<LabelViewControl>().ColumnSpan = 0;
                    groupHeader.GetControl<LabelViewControl>().AdditionalProperty["Content"] = " ";

                    newList.Add(groupHeader);
                    first = false;
                }
                newList.Add(item);
            }
            return newList;

        }

        #endregion

    }
}
